package com.allwees.bs.c.module.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.allwees.bs.c.module.user.dao.DeviceDao;
import com.allwees.bs.c.module.user.entity.DeviceEntity;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.repository.UserRepository;
import com.allwees.bs.c.module.user.service.DeviceService;
import com.allwees.bs.core.model.user.entity.DeviceModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceDao,DeviceEntity> implements DeviceService {

	@Autowired
    private UserRepository userRepository;

	@Override
	public void useDeviceLogin(String username, String deviceId) {
		log.info("===> user use device login,username:{},deviceId:{}",username,deviceId);
		UserEntity user = userRepository.findByEmailOrThirdId(username);
		if(user == null){
			log.info("===> user not found,username:{}",username);
			return;
		}

		String userUuid = user.getUuid();
		DeviceEntity device = this.lambdaQuery().eq(DeviceModel::getUserUuid, userUuid).one();
		if(device == null) {
			this.save(new DeviceEntity(userUuid, deviceId));
			return;
		}
		if(!StringUtils.equals(device.getJpushId(),deviceId)){
			this.lambdaUpdate().eq(DeviceModel::getUserUuid, userUuid).set(DeviceModel::getJpushId, deviceId);
		}
	}
}
